<?php
namespace Tbf\Bundle\TbfBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * 给事件dispatcher和事件subscriber上tag管理
 */
class SubscriberTagCompilerPass implements CompilerPassInterface
{
    /**
     * You can modify the container here before it is dumped to PHP code.
     *
     * @param ContainerBuilder $container
     *
     * @api
     */
    public function process(ContainerBuilder $container)
    {
        $dispatcher_list = $container->findTaggedServiceIds(
            'tbf.event_dispatcher'
        );
        foreach ($dispatcher_list as $dispatcher_id=>$dispatcher_attributes) {
            $dispatcher = $container->getDefinition($dispatcher_id);
            if (!empty($dispatcher_attributes[0]['subscriber_tag'])) {
                $subscriber_tag_name =  $dispatcher_attributes[0]['subscriber_tag'];
            } else {
                $subscriber_tag_name =   $dispatcher_id.'.subscriber';
            }
            $subscriber_list = $container->findTaggedServiceIds(
                $subscriber_tag_name
            );
            foreach ($subscriber_list as $subscriber_id=>$subscriber_attributes) {
                $dispatcher->addMethodCall(
                    'addSubscriber',
                    array(new Reference($subscriber_id))
                );
            }
        }

    }
}
